package com.wb.spring.boot.autoconfigure.register;

import com.ecwid.consul.v1.ConsulClient;
import com.wb.spring.boot.autoconfigure.annotation.ConditionalOnWbClientEnabled;
import com.wb.spring.boot.autoconfigure.WbProperties;
import com.wb.spring.boot.autoconfigure.WbRpcAutoConfiguration;
import com.wb.spring.boot.autoconfigure.load.Load;
import com.wb.spring.boot.autoconfigure.model.ServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.net.UnknownHostException;

/**
 * @author sw
 * @create 2023-03-03 9:43
 */

@Slf4j
@ConditionalOnWbClientEnabled
@ConditionalOnWbClientRegisterTypeConsul
@Configuration
@AutoConfigureAfter(value = {WbRpcAutoConfiguration.class, WbRedisRegisterAutoConfiguration.class})
public class WbConsulRegisterAutoConfiguration {

    @Bean
    public ConsulClient consulClient(WbProperties wbProperties) {
        WbProperties.ConsulRegister consulRegister = wbProperties.getConsulRegister();

        return new ConsulClient(consulRegister.getHost(), consulRegister.getPort());
    }

    @ConditionalOnBean(ConsulClient.class)
    @Bean
    public ConsulRegister consulRegister(Environment environment, ConsulClient consulClient, Load load) throws UnknownHostException {
        // 解析处本服务的基本信息
        ServerInfo serverInfo = new ServerInfo(environment);
        return new ConsulRegister(consulClient, serverInfo, load);
    }


}
